class LuckiesController < ApplicationController
  before_action :set_lucky, only: [:show, :edit, :update, :destroy]
  require 'csv'

  def update_setting_info
    type = Setting.find_by(id: params[:type_id])
    if type.present?
      type.write_attribute(params[:attr_name], params[:value])
      type.save
    end
    render json:true
  end

  def setting
    @settings = Setting.all
  end

  def download_lucky_list
    account_file_names, folder_array = [], []
    case params[:type].to_i
    when 1
      type_name = Setting.find_by(id: 1).type_name
      users = User.where(level: params[:type])
    when 2
      type_name = Setting.find_by(id: 2).type_name
      users = User.where(level: params[:type])
    when 3
      type_name = Setting.find_by(id: 3).type_name
      users = User.where(level: params[:type])
    when 4
      type_name = Setting.find_by(id: 4).type_name
      users = User.where(level: params[:type])
    when 5
      type_name = Setting.find_by(id: 5).type_name
      users = User.where(level: params[:type])
    when 6
      type_name = Setting.find_by(id: 6).type_name
      users = User.where(level: params[:type])
    when 7
      type_name = Setting.find_by(id: 7).type_name
      users = User.where(level: params[:type])
    when 8
      type_name = Setting.find_by(id: 8).type_name
      users = User.where(level: params[:type])
    end

    # folder = "public/export/#{Time.now.strftime('%Y-%m-%d-%H-%M-%S')}/#{type_name}.xls"
    # folder_array << folder
    # system("mkdir #{folder}")
    request.format = 'xls'
    filename = "#{type_name}_#{Time.now.strftime('%Y%m%d%H%M')}_export_data.xls"
    respond_to do |f|
      f.xls {send_data users.to_csv, filename: filename }
    end
  end

  def gen_anne_lucky_user
    type = Setting.find_by(id: 4)
    size = type.type_sum
    users = User.where(choose_party: true, go_ann: '是')
    shuffle_users = users.shuffle
    users.update_all(choose_anne_party: false)
    current_size = 0
    id_array = []
    shuffle_users.each do |s_user|
      current_size = current_size + s_user.dup.user_count
      if current_size == size
        id_array << s_user.id
        break
      elsif current_size < size
        id_array << s_user.id
      end
    end
    User.where(id: id_array).update_all(choose_anne_party: true)
    type.update_attributes(is_done: true)
    redirect_to show_luck_users_luckies_path
  end

  def pick_anne_user
    @users = User.where(choose_party: true)
  end

  def show_luck_users
    @users = User.where(level: params[:type])
  end

  def gen_lucky_user
    type = Setting.find_by(id: params[:type])
    size = type.type_sum
    current_size = 0
    id_array = []
    all_users = User.where(level: 0).where(user_type: params[:type])
    shuffle_users = all_users.order('random()')
    # users = shuffle_users.limit(size)
    shuffle_users.each do |s_user|
      origin_size = current_size
      current_size = current_size + s_user.dup.user_count
      if current_size == size
        id_array << s_user.id
        break
      elsif current_size < size
        id_array << s_user.id
      elsif current_size > size
        current_size = origin_size
      end
    end

    User.where(id: id_array).update_all(level: params[:type].to_i)
    type.update_attributes(is_done: true)
    redirect_to show_luck_users_luckies_path(type: type.id)
  end

  def upload_csv_data
    users_array = []
    file = params[:file]
    if File.extname(file.path) == ".xls"
      xlsx_data = Roo::Excel.new(file.path)
      xlsx_data.each_with_index do |data, index|
        next if index.zero?

        users_hash = {}
        users_hash[:name] = data[2].is_a?(Numeric) ? data[2].to_i.to_s.strip : data[2].to_s.strip
        users_hash[:phone] = data[4].is_a?(Numeric) ? data[4].to_i.to_s.strip : data[4].to_s.strip
        users_hash[:user_count] = data[5].is_a?(Numeric) ? data[5].to_i.to_s.strip : data[5].to_s.strip
        users_hash[:user_id] = data[1].is_a?(Numeric) ? data[1].to_i.to_s.strip : data[1].to_s.strip
        users_hash[:user_type] = data[0].to_s&.strip&.last
        users_array << User.new(users_hash)
      end
    elsif File.extname(file.path) == ".xlsx"
      creek = Creek::Book.new(file.path)
      xlsx_data = creek.sheets[0]
      
      
      xlsx_data.simple_rows.each_with_index do |data, index|
        next if index.zero?

        users_hash = {}
        users_hash[:name] = data['C'].is_a?(Numeric) ? data['C'].to_i.to_s.strip : data['C'].to_s.strip
        users_hash[:phone] = data['E'].is_a?(Numeric) ? data['E'].to_i.to_s.strip : data['E'].to_s.strip
        users_hash[:user_count] = data['F'].is_a?(Numeric) ? data['F'].to_i.to_s.strip : data['F'].to_s.strip
        users_hash[:user_id] = data['B'].is_a?(Numeric) ? data['B'].to_i.to_s.strip : data['B'].to_s.strip
        users_hash[:user_type] = data['A'].to_s&.strip&.last
        users_array << User.new(users_hash)
      end
    else
      return render text: '文件格式不正确'
    end
    User.delete_all
    # #批量新建用户
    # need_imports = []
    # users_array[1..-1].each do |user|
    #   need_imports << User.new(name: user[:name],
    #                            phone: user[:phone],
    #                            user_count: user[:user_count],
    #                            user_id: user[:user_id],
    #                            user_type: user[:user_type])
    # end
    User.import users_array
    #一个一个新建用户
    # User.create(users_array)
    Setting.all.update_all(is_done: false)
    redirect_to setting_luckies_path
  end

  def pick_lucky
    @users = User.where(level: 0)
    @type_id = params[:type_id]
  end

  # GET /luckies
  # GET /luckies.json
  def index
    @luckies = Lucky.all
  end

  # GET /luckies/1
  # GET /luckies/1.json
  def show
  end

  # GET /luckies/new
  def new
    @lucky = Lucky.new
  end

  # GET /luckies/1/edit
  def edit
  end

  # POST /luckies
  # POST /luckies.json
  def create
    @lucky = Lucky.new(lucky_params)

    respond_to do |format|
      if @lucky.save
        format.html { redirect_to @lucky, notice: 'Lucky was successfully created.' }
        format.json { render :show, status: :created, location: @lucky }
      else
        format.html { render :new }
        format.json { render json: @lucky.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /luckies/1
  # PATCH/PUT /luckies/1.json
  def update
    respond_to do |format|
      if @lucky.update(lucky_params)
        format.html { redirect_to @lucky, notice: 'Lucky was successfully updated.' }
        format.json { render :show, status: :ok, location: @lucky }
      else
        format.html { render :edit }
        format.json { render json: @lucky.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /luckies/1
  # DELETE /luckies/1.json
  def destroy
    @lucky.destroy
    respond_to do |format|
      format.html { redirect_to luckies_url, notice: 'Lucky was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_lucky
      @lucky = Lucky.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def lucky_params
      params.fetch(:lucky, {})
    end
end
